package com.openatc.agent.service.impl;

import com.google.gson.JsonElement;
import com.openatc.agent.service.FeatureRequest;
import com.openatc.agent.service.FeatureService;
import com.openatc.agent.utils.RedisTemplateUtil;
import com.openatc.comm.data.MessageData;
import com.openatc.core.model.InnerError;
import com.openatc.core.model.RESTRet;
import com.openatc.core.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

import static com.openatc.core.common.IErrorEnumImplInner.E_109;
import static com.openatc.core.common.IErrorEnumImplInner.E_110;

/**
 * @Classname FeaturePlanRequest
 * @Description 计划参数处理类
 * @Date 2022/7/20 9:07
 * @Created by panleilei
 */
@Service(value = "feature/plan")
public class FeaturePlanRequest extends FeatureRequest {

    @Autowired
    private CommServiceDown commServiceDown;
    @Autowired
    private FeatureService featureService;
    @Autowired
    private RedisTemplateUtil redisTemplateUtil;
    private static final String keyType = "response:feature/plan:";
    /**
     * 成功下载计划参数
     * @param requestData
     * @param responseData
     * @return
     */
    @Override
    public RESTRet successSetProcess(MessageData requestData, RESTRet responseData) {
        String agentid = requestData.getAgentid();
//        RESTRet restRet = featureService.deleteFeatureByAgentid(agentid);
//        if (!restRet.isSuccess()) {
//            logger.warning("MsgPostHandler process: clear feature failed!");
//        }
        redisTemplateUtil.delete("asc:feature/all:" + agentid);
        updatePlanCache(requestData.getAgentid(),requestData);
        updateDbPlan(requestData);

        // 更新dev字段表中的计划数量
        int row = updateDevPlanCount(requestData);
        if (row == 0) {
            logger.warning("update dev plan count failed!");
        }
        return super.successSetProcess(requestData, responseData);
    }

    /**
     * 更新数据库中计划参数
     * @param requestData
     */
    private void updateDbPlan(MessageData requestData) {
        String agentId = requestData.getAgentid();
        // 如果数据库中没有特征参数数据，不更新
        MessageData feature = featureService.getFeatures(agentId);
        if (feature == null) {
            logger.warning("DB feature is empty,do not update!");
            return;
        }
        // 如果数据库中有特征参数数据，增量更新相位数据
        JsonElement data = feature.getData();
        if (data == null) {
            logger.warning("DB feature is empty,do not update!");
            return;
        }
        JsonElement planList = requestData.getData().getAsJsonObject().get("planList");
        data.getAsJsonObject().add("planList",planList);
        featureService.saveFeatureAll(feature);
    }

    private int updateDevPlanCount(MessageData requestData) {
        String dataSourceFieldName = "planList";
        return commServiceDown.updateDevFeatureCount(dataSourceFieldName,FieldName.PLAN_COUNT,requestData);
    }

    /**
     * 成功上载计划参数
     * @param requestData
     * @param responseRet
     * @return
     */
    @Override
    public RESTRet successGetProcess(MessageData requestData, RESTRet responseRet) {
        MessageData responseData = (MessageData) responseRet.getData();
        updatePlanCache(requestData.getAgentid(),responseData);
        updateDbPlan(requestData);
        // 更新dev字段表中的计划数量
        int row = updateDevPlanCount(responseData);
        if (row == 0) {
            logger.warning("update dev plan count failed!");
        }
        return super.successGetProcess(requestData, responseRet);
    }

    /**
     * 请求方案参数失败
     * @param requestData
     * @param responseData
     * @return
     */
    @Override
    public RESTRet failureGetProcess(MessageData requestData, RESTRet responseData) {
        // 从缓存中获取参数
        InnerError innerError1 = (InnerError) responseData.getData();
        if (innerError1.getErrorCode().equals(E_110.getErrorCode())) {
            return redisTemplateUtil.getCacheData(requestData);
        }
        else if(innerError1.getErrorCode().equals(E_109.getErrorCode())){
            return redisTemplateUtil.getCacheData(requestData);
        }
        return super.failureGetProcess(requestData,responseData);
    }


    /**
     * 更新方案缓存数据
     * @param agentid
     * @param data
     */
    private void updatePlanCache(String agentid, MessageData data) {
        String key = keyType + agentid;
        // 不改变MessageData原始结构，借助gson进行深拷贝
        MessageData deepCopy = gson.fromJson(gson.toJsonTree(data),MessageData.class);
        deepCopy.setOperation("get-response");
//        deepCopy.setInfotype("feature/pattern");
        deepCopy.setCreatetime(DateUtil.date2str(new Date()));
        redisTemplateUtil.setValue(key,gson.toJson(deepCopy));
    }
}
